﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WeighClient.Model;
using WeighClient.Utils;

namespace WeighClient.Windows
{
    /// <summary>
    /// IndexWindow.xaml 的交互逻辑
    /// </summary>
    public partial class IndexWindow : Window
    {
        Thread readCardThread = null;
        Block block = null;
        delegate void MyDelegate(Object value);
        SynchronizationContext _syncContext = null;
        static string ledIp = "";
        SaleInfoWindow saleInfoWindow;
        PurchaseInfoWindow purchaseInfoWindow;
        Bill Bill;
        int m_iInit1 = -1;
        //int m_iStatus1 = -1;
        int m_iInit2 = -1;
        //int m_iStatus2 = -1;

        public IndexWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            Bill = new Bill();
            this.Loaded += Window_Load;
            this.Unloaded += Window_UnLoad;
            CommonInterface.PortType = "USB";
            CommonInterface.PortPara = "0400C35A";
            CommonInterface.ExtendPara = "";
           

        }

 
        private void Window_UnLoad(object sender, RoutedEventArgs e)
        {
            if (m_iInit1==0)
            {
                MsPrinterUtils.SetClose();
            }
        }

        private void Window_Load(object sender, RoutedEventArgs e)
        {
            try
            {
                HttpServer server = App.GetHttpServer();
                if (null != server)
                {
                    HttpServer.sendMsgEvent += Server_sendMsgEvent;
                }

            }
            catch (Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Error");
                MessageBox.Show(ex.ToString());
            }


            //string idcard = App.GetConfig().IDCard;
            //if ("1".Equals(idcard))
            //{


            //    int handle = CommonInterface.OpenDevice("USB", "0400C35A", "");
            //    if (handle <= 0)
            //    {
            //        //MessageBox.Show("打开设备失败，错误代码：" + handle.ToString());
            //        return;
            //    }
            //}
            if (App.GetConfig().IfPrint.Equals("0"))
            {
                try
                {
                    //SetTraceLog(1);
                    if (m_iInit1 != 0)
                    {
                        int t1 = 0x519;
                        int p1 = 0x2015;
                        MsPrinterUtils.SetDevVIDPID(t1, p1);
                        MsPrinterUtils.SetUsbportauto();
                        m_iInit1 = MsPrinterUtils.SetInit();
                        int r1 = MsPrinterUtils.GetStatus();
                       // MessageBox.Show(m_iInit1 + "hhhhhh" + r1);

                        int t2 = 0x519;
                        int p2 = 0x2013;
                        MsPrinterUtils.SetDevVIDPID(t2, p2);
                        MsPrinterUtils.SetUsbportauto();
                        m_iInit2 = MsPrinterUtils.SetInit();
                        int r2 = MsPrinterUtils.GetStatus();
                        //MessageBox.Show(m_iInit2 + "hhhhhh" + r2);
                        if (m_iInit1 == 0)
                        {

                            MsPrinterUtils.SetCommandmode(3);
                        }
                        else
                        {
                            // MessageBox.Show("InitPrinter failure!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    else
                    {

                        m_iInit1 = -1;
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

                


        }


        private void Server_sendMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(d, obj);
        }

        void DealMessage(Object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");
            String direction = (String)jsonObj.GetValue("direction");
            string printer1 = App.GetConfig().Printer01;
            string printer2 = App.GetConfig().Printer02;

            if ("LoadBillInfo".Equals(type))
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                //_syncContext.Post(AddLogTxt, detailObj.ToString());

                Bill = Json2Bill(detailJSON);
                //Bill bill = new Bill();
                if ("销售".Equals(Bill.busitype))
                {
                    saleInfoWindow = new SaleInfoWindow(Bill);
                    saleInfoWindow.Show();
                }
                else
                {
                    purchaseInfoWindow = new PurchaseInfoWindow(Bill);
                    purchaseInfoWindow.Show();
                }
                ////向集控端发送提单信息
                //JObject jsonParamObj = new JObject();
                //jsonParamObj.Add("from", "client");
                //jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                //jsonParamObj.Add("type", "BillInfo");
                //jsonParamObj.Add("billObj", JObject.FromObject(bill));

                ////_syncContext.Post(SendMqMessage, jsonParamObj);
                //bool result = SendMqMessage(jsonParamObj);
                //if (!result)
                //{
                //    result = SendMqMessage(jsonParamObj);
                //    if (!result)
                //    {
                //        JObject json = new JObject();
                //        json.Add("from", "client");
                //        json.Add("clientId", App.GetConfig().DeviceCode);
                //        json.Add("type", "VoiceAndLed");
                //        json.Add("voiceMsg", "单据信息发送失败");
                //        SendMqMessage(json);
                //    }
                //}
                //_syncContext.Post(SetBillInfo, bill);
            }
            //else if ("openDevice".Equals(type))
            //{
            //    string idcard = App.GetConfig().IDCard;
            //    if ("1".Equals(idcard))
            //    {


            //        int handle = CommonInterface.OpenDevice("USB", "0400C35A", "");
            //        if (handle <= 0)
            //        {
            //            //MessageBox.Show("打开设备失败，错误代码：" + handle.ToString());
            //            return;
            //        }
            //    }
            //}
            else if ("openDevice".Equals(type))
            {
                if ("1".Equals(App.GetConfig().IDCard))
                {
                    String port = "";
                    if ("left".Equals(direction))
                    {
                        port = App.GetConfig().IDCardPort1;
                    }
                    else
                    {
                        port = App.GetConfig().IDCardPort2;
                    }

                    String rate = App.GetConfig().IDCardPortBaudRate;
                    int handle = CommonInterface.OpenDevice(port, rate, "");
                    if (handle <= 0)
                    {
                        //MessageBox.Show("打开设备失败，错误代码：" + handle.ToString());
                        return;
                    }
                }
            }
            else if ("closeIdDevice".Equals(type))
            {
                int Handle = CommonInterface.GetCurrentDevice();

                int ret1 = CommonInterface.CloseDevice();
                if (ret1 != 0)
                {
                    //MessageBox.Show("关闭设备失败，错误代码：" + ret1.ToString());
                    return;
                }
            }
            else if ("block".Equals(type))//遮盖
            {
                String blockcode = (String)jsonObj.GetValue("blockcode");
                if ("open" == blockcode)
                {
                    if (null == block)
                    {
                        block = new Block();
                        block.Show();

                    }
                }
                else if ("close" == blockcode)
                {
                    if (null != block)
                    {
                        block.Close();
                        block = null;
                    }


                }


            }
        
            else if ("readCardNo".Equals(type))
            {
                string facId = "";
                if ("1".Equals(App.GetConfig().IDCard))
                {
                    String port = "";

                    StringBuilder IdCardInfo = new StringBuilder(409600);
                    int ret = CommonInterface.SdtReadCard(0, 1, IdCardInfo, 0);
                    if (ret == 0)
                    {
                        string[] CardInfo = IdCardInfo.ToString().Split(':');

                        String name = CardInfo[1];
                        String idNum = CardInfo[9];
                        facId = idNum;
                        //MessageBox.Show(idNum);                    

                    }
                }
                else
                {
                    facId = App.GetConfig().IDCardNumber;
                }
                JObject cardNoJson = new JObject();
                //cardNoJson.Add("facCardNo", facId);

                cardNoJson.Add("facCardNo", facId);
                SendMessageUtils.SendNodeRedMsg("PostMessage/facCardNo", cardNoJson);
            }
            else if ("UploadBillSuccess".Equals(type))
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                Bill = Json2Bill(detailJSON);
                //if ("销售".Equals(Bill.busitype))
                //{
                //    saleInfoWindow.Close();
                //    saleInfoWindow = new SaleInfoWindow(Bill);
                //    saleInfoWindow.Show();
                //}
                //else
                //{
                //    purchaseInfoWindow.Close();
                //    purchaseInfoWindow = new PurchaseInfoWindow(Bill);
                //    purchaseInfoWindow.Show();
                //}

                //Bill bills = queryBillDetail(bill.id);
                //bill.pizhong = bills.pizhong;
                //bill.maozhong = bills.maozhong;
                //bill.jingzhong = bills.jingzhong;
                //bill.cmzName = bills.cmzName;
                //bill.cpzName = bills.cpzName;
                //bill.orderCode = bills.orderCode;
                //bill.storeCompanyName = bills.storeCompanyName;
                //_syncContext.Post(SetBillInfo, bill);
                //string weigh = bill.weigh;
                //String txt1 = "";
                //String txt2 = "";
                //String txt3 = "";
                //String jstxt = "";
                //String successmsg = "";
                //if (bill.print == "1")
                //{
                //    if (bill.jstype != null && bill.jstype.Equals("success"))
                //    {
                //        jstxt = "已结算，请将卡放至回收箱";
                //        successmsg = bill.successMsg;
                //    }
                //    else if (bill.jstype != null && bill.jstype.Equals("fail"))
                //    {
                //        jstxt = "未结算，请取卡下磅到大厅结算";
                //        successmsg = bill.successMsg;

                //    }
                //    else
                //    {
                //        jstxt = "";
                //    }
                //}

                //if (bill.busitype.Equals("销售"))
                //{
                //    if (bill.print == "0")
                //    {
                //        if (bill.loadPlace == "-1")
                //        {
                //            txt1 = bill.carNo;
                //            txt2 = "皮重" + bill.pizhong;
                //        }
                //        else
                //        {
                //            txt1 = bill.carNo;
                //            txt2 = "皮重" + bill.pizhong;
                //        }
                //        //this.sendMsg(txt1,txt2,true);
                //        //this.sendMsg(txt2,txt1,"计量完成，取卡下磅","single");
                //    }
                //    else if (bill.print == "1")
                //    {
                //        String jz = "";
                //        jz = Convert.ToDouble(bill.jingzhong).ToString("0.00");
                //        txt1 = bill.carNo;
                //        //txt2 = "毛重" + bill.maozhong + "吨,皮重" + bill.pizhong + "吨,净重" + jz + "吨";
                //        txt2 = "净重" + jz;
                //        txt3 = "皮重" + bill.pizhong + "毛重" + bill.jingzhong;
                //        //this.sendMsg(txt1+txt2,txt3, "计量完成,"+jstxt,"double");
                //        //this.sendMsg(txt1,txt2,true);
                //    }
                //}
                //else
                //{
                //    if (bill.print == "0")
                //    {
                //        txt1 = bill.carNo;
                //        txt2 = "毛重" + bill.maozhong;
                //        //this.sendMsg(txt2, txt1, "计量完成，取卡下磅", "single");
                //    }
                //    else if (bill.print == "1")
                //    {
                //        String jz = "";
                //        jz = Convert.ToDouble(bill.jingzhong).ToString("0.00");
                //        txt1 = bill.carNo;
                //        txt2 = "净重" + jz;
                //        txt3 = "皮重" + bill.pizhong + ",毛重" + bill.jingzhong;
                //        //this.sendMsg(txt1 + txt2, txt3, "计量完成,"+jstxt, "double");

                //    }
                //}

                if (App.GetConfig().IfPrint.Equals("0"))
                {

                    if (Bill.print == "1")
                    {
                      //  PrintUtils.printWeighOrder(Bill, printer1);
                        //检查打印机是否有纸
                        try
                        {
                            int m_iStatus = -1;
                            int t1 = 0x519;
                            int p1 = 0x2015;
                            MsPrinterUtils.SetDevVIDPID(t1, p1);
                            MsPrinterUtils.SetUsbportauto();
                            m_iInit1 = MsPrinterUtils.SetInit();//初始化打印机
                            m_iStatus = MsPrinterUtils.GetStatus();//获取打印机状态
                               MessageBox.Show("111打印机状态为"+m_iStatus);
                            if (m_iStatus == 0 || m_iStatus == 8)
                            {
                                PrintUtils.printWeighOrder(Bill, printer1);

                            }
                            else
                            {
                                MessageBox.Show("222打印机状态为" + m_iStatus);

                                if (m_iStatus == 7)
                                {
                                    JObject reqObj = new JObject();
                                    reqObj.Add("type", "PrinterStatus");
                                    reqObj.Add("message", "主打印机缺纸");
                                    SendNodeRedMessage("PostMessage/PrinterStatus", reqObj);
                                    m_iStatus = -1;
                                    int t2 = 0x519;
                                    int p2 = 0x2013;
                                    MsPrinterUtils.SetDevVIDPID(t2, p2);
                                    MsPrinterUtils.SetUsbportauto();
                                    m_iInit2 = MsPrinterUtils.SetInit();
                                    m_iStatus = MsPrinterUtils.GetStatus();
                                    // MessageBox.Show("333打印机状态为" + m_iStatus);

                                    if (m_iStatus == 0)
                                    {
                                        PrintUtils.printWeighOrder(Bill, printer2);

                                    }
                                    else if (m_iStatus != 7)
                                    {
                                        //MessageBox.Show("444打印机状态为" + m_iStatus);

                                        JObject reqObj1 = new JObject();
                                        reqObj1.Add("type", "PrinterStatus");
                                        reqObj1.Add("message", "备用打印机缺纸");
                                        SendNodeRedMessage("PostMessage/PrinterStatus", reqObj1);
                                    }
                                }
                                else
                                {
                                    JObject reqObj = new JObject();
                                    reqObj.Add("type", "PrinterStatus");
                                    reqObj.Add("message", "主打印机状态异常");
                                    SendNodeRedMessage("PostMessage/PrinterStatus", reqObj);
                                    int t2 = 0x519;
                                    int p2 = 0x2013;
                                    MsPrinterUtils.SetDevVIDPID(t2, p2);
                                    MsPrinterUtils.SetUsbportauto();
                                    m_iInit2 = MsPrinterUtils.SetInit();
                                    m_iStatus = MsPrinterUtils.GetStatus();
                                    if (m_iStatus == 0 || m_iStatus == 8)
                                    {
                                        PrintUtils.printWeighOrder(Bill, printer2);

                                    }
                                    else
                                    {
                                        JObject reqObj1 = new JObject();
                                        if (m_iStatus == 7)
                                        {
                                            reqObj1.Add("type", "PrinterStatus");
                                            reqObj1.Add("message", "备用打印机缺纸");
                                            SendNodeRedMessage("PostMessage/PrinterStatus", reqObj1);
                                        }
                                        else
                                        {
                                            reqObj1.Add("type", "PrinterStatus");
                                            reqObj1.Add("message", "备用打印机状态异常");
                                            SendNodeRedMessage("PostMessage/PrinterStatus", reqObj1);
                                        }
                                        //JObject reqObj = new JObject();

                                    }
                                }



                            }



                            //if (m_iStatus1 != 0)
                            //{
                            //    if (m_iStatus1 == 7 || m_iStatus1 == 8)
                            //    {
                            //        MessageBox.Show("打印机纸张缺失");
                            //        return;
                            //    }
                            //    MessageBox.Show("打印机异常");
                            //    return;
                            //}
                            //m_iStatus1 = MsPrinterUtils.GetStatusspecial();
                            //if (m_iStatus1 != 0)
                            //{
                            //    MessageBox.Show("打印机异常");
                            //    return;
                            //}
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("打印机异常");
                        }


                        //PrintUtils.printWeighOrder(Bill, printer1);

                    }
                }

                //_syncContext.Post(AddLogMessage, new LogInfo(txt1+txt2+"吨,计量完成"+successmsg));
            }
            else if ("ErrorMessage".Equals(type))
            {
                string errorMsg = (string)jsonObj.GetValue("msg");
                if (saleInfoWindow != null)
                {
                    saleInfoWindow.LabelMsg(errorMsg);//报警信息
                }
                if(purchaseInfoWindow != null)
                {
                    purchaseInfoWindow.LabelMsg(errorMsg);
                }

            }else if ("UpdateBill".Equals(type))//更新数据
            {
                JObject detailJSON = (JObject)jsonObj.GetValue("detail");
                Bill = Json2Bill(detailJSON);
                //Bill bill = new Bill();
                if ("销售".Equals(Bill.busitype))
                {
                    saleInfoWindow.UpdateBill(Bill);
                }
                else
                {
                    purchaseInfoWindow.UpdateBill(Bill);
                }
            }
            else if ("Complete".Equals(type))
            {

       /*         if (saleInfoWindow != null)
                {
                    saleInfoWindow.Close();
                }
                if (purchaseInfoWindow != null)
                {
                    purchaseInfoWindow.Close();
                }*/
                if ("销售".Equals(Bill.busitype))
                {
                    saleInfoWindow.Close();

                }
                else if ("采购".Equals(Bill.busitype))
                {
                    purchaseInfoWindow.Close();

                } else 
                {
                    // purchaseInfoWindow.Close();
                }

            }

            else if ("PrintSmallTicket".Equals(type))
            {
                Console.WriteLine("PrintSmallTicket...");

                JObject billObj = (JObject)jsonObj.GetValue("billObj");
                Bill bill = Json2Bill(billObj);

                PrintUtils.printWeighOrder(bill, printer1);
            }
        }

        Bill Json2Bill(JObject detailJSON)
        {
            String tongPi = (String)detailJSON.GetValue("tongPi");//桶皮重
            String id = (String)detailJSON.GetValue("id");
            String orderCode = (String)detailJSON.GetValue("billNo");
            String carNo = (String)detailJSON.GetValue("carNumber");
            String productName = (String)detailJSON.GetValue("productName");
            String corpName = (String)detailJSON.GetValue("companyName");
            //String corpName = (String)detailJSON.GetValue("companyName");
            String position = (String)detailJSON.GetValue("position");
            String planNum = (String)detailJSON.GetValue("planNum");
            String _guid = (String)detailJSON.GetValue("guid");
            String weigh = (String)detailJSON.GetValue("weigh");
            String personWeigh01 = (String)detailJSON.GetValue("personWeight01");
            String personWeigh02 = (String)detailJSON.GetValue("personWeight02");
            String loadPlaceName = (String)detailJSON.GetValue("loadPlaceName");
            String materialName = (String)detailJSON.GetValue("materialName");
            String cpzTime = (String)detailJSON.GetValue("cpzTime");
            String cmzTime = (String)detailJSON.GetValue("cmzTime");
            String price = (String)detailJSON.GetValue("price");
            String customerName = (String)detailJSON.GetValue("corpName");
            String fnpolicemsg = (String)detailJSON.GetValue("fnpolicemsg");
            Bill bill = new Bill();

            bill.id = id;
            bill.tongPi = tongPi;
            bill.orderCode = orderCode;
            bill.carNo = carNo;
            bill.productName = productName;
            bill.corpName = corpName;
            bill.position = position;
            bill.planNum = planNum;
            bill.videoCarNo = App.GetRunTimeVariable().CarNo;
            bill.personWeight01 = personWeigh01;
            bill.personWeight02 = personWeigh02;
            bill.loadPlace = loadPlaceName;
            bill.cpzTime = cpzTime;
            bill.cmzTime = cmzTime;
            bill.price = price;
            bill.customerName = customerName;
            bill.qianbiao = (String)detailJSON.GetValue("fySurfaceFront");
            bill.lossNum = (String)detailJSON.GetValue("lossNum");
            bill.houbiao = (String)detailJSON.GetValue("fySurfaceBack");
            bill.fnpolicemsg = fnpolicemsg;
            bill.weightStatus = (String)detailJSON.GetValue("weightStatus");
            bill.yuanfaNum = (String)detailJSON.GetValue("yuanfaNum");
            bill.chazhi = (String)detailJSON.GetValue("chazhi");
            bill.fayou = (String)detailJSON.GetValue("fayou");
            bill.pizhong = (String)detailJSON.GetValue("pizhong");
            bill.maozhong = (String)detailJSON.GetValue("maozhong");
            bill.jingzhong = (String)detailJSON.GetValue("jingzhong");
            bill.qianbiao = (String)detailJSON.GetValue("qianbiao");
            bill.houbiao = (String)detailJSON.GetValue("houbiao");
            bill.busitype = (String)detailJSON.GetValue("busitype");
            bill.operatorName = (String)detailJSON.GetValue("operatorName");
            bill.print = (String)detailJSON.GetValue("print");
            bill.guid = _guid;
            bill.weigh = (String)detailJSON.GetValue("weigh");


            bill.materialName = materialName;

            return bill;
        }


        private void SendNodeRedMessage(String path, JObject reqObj)
        {
            try
            {
                String result = HttpPostHelper.doHttpPost(App.GetConfig().NodeRedUrl + path, reqObj.ToString());

            }
            catch (Exception ex) { }
        }
    }
}
